package com.example.demo2.Util.Filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest res = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        if (res.getServletPath().equals("/register.jsp") || res.getServletPath().equals("/login.jsp")||res.getServletPath().equals("/loginServlet")) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            Object user = res.getSession().getAttribute("user");
            if (user == null) {
                resp.getWriter().write("Please log in first, thank you!！");

            }else {
                filterChain.doFilter(servletRequest, servletResponse);
            }
            if (res.getSession().getAttribute("isLogin").equals("true")) {
                filterChain.doFilter(servletRequest, servletResponse);
            }
        }
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
